<template>
  <div class="index">
    <!-- 顶部栏 -->
    <div class="header">
      <div class="logo">
        <span class="iconfont iconnew"></span>
      </div>
      <div class="search" @click="$router.push({ name: 'Search' })">
        <van-icon name="search" />
        <span>搜索商品</span>
      </div>
      <div class="user" @click="User">
        <van-icon name="manager-o" />
      </div>
    </div>
    <!-- 标签页 -->
    <!-- active就代表当前默认选中的标签项：那么我们就应该加载这个选项的新闻数据 -->
    <van-tabs v-model="active" swipeable sticky>
      <van-tab
        v-for="(value, index) in catelist"
        :key="index"
        :title="value.name"
        swipeable
      >
        <!-- 上拉加载数据 -->
        <van-list
          v-model="value.loading"
          :finished="value.finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <!-- 下拉刷新 -->
          <van-pull-refresh v-model="value.isLoading" @refresh="onRefresh">
            <!-- 新闻模块 -->
            <articleBlock
              v-for="(item, index) in value.postlist"
              :post="item"
              :key="index"
            ></articleBlock>
          </van-pull-refresh>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { getCateList } from "@/apis/category";
import { getPostList } from "@/apis/post";
import articleBlock from "@/components/articleBlock.vue";
export default {
  data() {
    return {
      catelist: [],
      active: localStorage.getItem("toutiao_59_token") ? 1 : 0,
    };
  },
  components: {
    articleBlock,
  },
  methods: {
    async init() {
      // 获取当前栏目的新闻数据
      let res = await getPostList({
        category: this.catelist[this.active].id,
        pageIndex: this.catelist[this.active].pageIndex, // 获取当前栏目中的页码
        pageSize: this.catelist[this.active].pageSize, // 获取当前栏目中的每页显示的数量
      });
      console.log(res.data.data);
      // 将获取数据存储（追加）到当前栏目的postlist数组中
      this.catelist[this.active].postlist.push(...res.data.data);
    },
    // 下拉刷新数据
    onRefresh() {
      this.catelist[this.active].postlist.length = 0; // 清空数据
      this.catelist[this.active].pageIndex = 1; // 重置页码到1
      // 重新请求数据
      // console.log(this.catelist[this.active].category);
      setTimeout(async () => {
        // 不管之前是否还有数据，将可能被重置的finished重置为false
        this.catelist[this.active].finished = false;
        let res = await this.init();
        console.log(res);
        this.catelist[this.active].isLoading = false;
      }, 200);
    },
    // 上拉加载更多数据
    onLoad() {
      // console.log(1);
      this.catelist[this.active].pageIndex++;
      console.log(this.catelist[this.active].pageIndex);

      setTimeout(async () => {
        let res = await this.init();
        console.log(res);
        this.catelist[this.active].loading = false;
        this.catelist[this.active].finished = true; //没有更多数据了
        // 重置下拉刷新的状态
        this.catelist[this.active].isLoading = false;
      }, 200);
    },
    // 用户跳转
    User() {
      if (localStorage.getItem("toutiao_59_id")) {
        this.$router.push({
          path: "/personal/" + localStorage.getItem("toutiao_59_id"),
        });
      } else {
        this.$router.push({ path: "/login" });
        this.$toast.fail("请先登录");
      }
    },
  },

  async activated() {
    // 点击加号
    document.querySelector(".van-sticky").onclick = (e) => {
      // console.log(e.target.className);
      // 伪元素不能绑定事件，所以可以用类名来为他添加事件
      if (e.target.className == "van-sticky") {
        this.$router.push({ name: "cateManager" });
      }
    };

    //如果本地储存有数据，优先加载本地
    // console.log(localStorage.getItem("toutiao_59_cateList"));
    let toutiao_59_cateList = localStorage.getItem("toutiao_59_cateList");
    if (toutiao_59_cateList) {
      this.catelist = JSON.parse(toutiao_59_cateList);
      // console.log(this.catelist);
      // 如果有登录，就加载关注和头条
      let toutiao_59_token = localStorage.getItem("toutiao_59_token");
      if (toutiao_59_token) {
        this.catelist.unshift(
          { id: 0, is_top: 1, name: "关注" },
          { id: 999, is_top: 1, name: "头条" }
        );
        // 如果没有登录，就加载头条
      } else {
        this.catelist.unshift({ id: 999, is_top: 1, name: "头条" });
      }
    } else {
      // 实现栏目数据的动态渲染
      let res = await getCateList();
      // console.log(res);
      this.catelist = res.data.data;
    }

    // console.log(this.catelist);
    // 数据改造:每个栏目有属于自己的新闻数据,且能找到的操作互不干扰,当前栏目数据结构不能满足这个需求
    this.catelist = this.catelist.map((v) => {
      return {
        ...v,
        postlist: [], // 添加了存储这个栏目新闻数据的数组
        pageIndex: 1, // 当前栏目的页码
        pageSize: 4, // 当前栏目每页显示的数量
        loading: false, // 当前栏目的上拉加载的状态，为true说明下在加载中
        finished: false, // 当前栏目数据是否全部加载完毕，为true说明没有更多数据了
        isLoading: false, // 当前栏目的下拉刷新的状态，为false说明加载完成
      };
    });
    console.log(this.catelist);
    // console.log(this.active);
    // 获取当前栏目的新闻数据
    // console.log(this.catelist[this.active].pageSize);
    let id = this.catelist[this.active].id;
    this.init({
      pageIndex: this.catelist[this.active].pageIndex,
      pageSize: this.catelist[this.active].pageSize,
      category: id,
    });
  },
  watch: {
    active() {
      // console.log("触发了");
      // console.log(this.active); // 索引
      let id = this.catelist[this.active].id;
      // console.log(this.catelist[this.active].postlist.length);
      // 当页面加载过之后，不再发请求
      if (this.catelist[this.active].postlist.length === 0) {
        // 获取当前栏目的新闻数据
        this.init({
          pageIndex: this.catelist[this.active].pageIndex,
          pageSize: this.catelist[this.active].pageSize,
          category: id,
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
// 标签栏
/deep/.van-sticky {
  padding-right: 50px;
  background-color: #fff;
  // 伪元素
  &::after {
    content: "+";
    position: absolute;
    width: 44px;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-size: 22px;
    font-weight: 700;
    right: 0;
    top: 0;
  }
}
.index {
  .header {
    height: 40px;
    display: flex;
    justify-content: space-between;
    background-color: #f00;
    align-items: center;
    color: #fff;
  }
  .search {
    flex: 1;
    height: 30px;
    background-color: rgba(255, 255, 255, 0.4);
    border-radius: 15px;
    text-align: center;
    line-height: 30px;
    .van-icon {
      font-size: 16px;
    }
  }
  .van-icon {
    font-size: 24px;
    padding: 0 10px;
  }
  .iconfont {
    font-size: 50px;
    padding: 0 10px;
  }
}
</style>